<template>
  <div class="app-container">
    <el-form :inline="true" :model="filters" class="demo-form-inline filter-container" ref="refForm">
      <el-form-item label="主题：" prop="name">
        <el-input v-model="filters.name" @keyup.enter.native="gridSearch"></el-input>
      </el-form-item>
      <el-form-item label="账户类型" prop="userType">
        <el-select v-model="filters.userType">
          <el-option
            v-for="item in consts.ACCOUNT_TYPE"
            :key="item.value"
            :label="item.title"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="显示端" prop="showClient">
        <el-select
          v-model="filters.showClient"
          :collapse-tags="true"
          placeholder="请选择显示端"
          :multiple="true"
        >
          <el-option
            v-for="item in consts.ADVER_DEVICE_TYPE_ACTIVE"
            :key="item.value"
            :label="item.title"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="filters.status">
          <el-option
            v-for="item in consts.NOTICE_STATUS"
            :key="item.value"
            :label="item.title"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="最后编辑" prop="operator">
        <el-input v-model="filters.operator" @keyup.enter.native="gridSearch"></el-input>
      </el-form-item>

      <!-- <el-form-item label="操作人" prop="operator">
        <el-select v-model="filters.operator">
          <el-option v-for="item in operatorList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>-->
      <el-form-item label="发布时间：" prop="time">
        <el-date-picker
          v-model="filters.time"
          class="filter-item"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
          value-format="yyyy-MM-dd HH:mm:ss"
          align="left"
        ></el-date-picker>
      </el-form-item>

      <el-button type="primary" v-waves icon="el-icon-search" @click="gridSearch">搜索</el-button>
      <el-button type="primary" v-waves @click="selfResetForm('refForm')">重置</el-button>
    </el-form>
    <el-button
      v-if="roleCheck('create')"
      type="primary"
      @click="openDialog({dialogName: 'notice-edit',props: {}})"
      style="margin:10px 0"
    >新建公告</el-button>
    <el-table
      :data="tableData.list"
      v-loading="loading"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="主题" align="center">
        <template slot-scope="{row}">
          <el-tooltip effect="dark" :content="row.name" placement="top">
            <span class="text-nowrap">{{row.name}}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="简介" align="center">
        <template slot-scope="{row}">
          <el-tooltip effect="dark" :content="row.summary" placement="top">
            <span class="text-nowrap">{{row.summary}}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center">
        <template slot-scope="{row}">{{row.effectiveDate | toTime}}</template>
      </el-table-column>
      <el-table-column label="账户类型" align="center">
        <template slot-scope="{row}">{{row.userType | toConverter('ACCOUNT_TYPE')}}</template>
      </el-table-column>
      <el-table-column label="显示端" align="center">
        <template
          slot-scope="{row}"
        >{{row.showClientArray | toConverter('ADVER_DEVICE_TYPE_ACTIVE') | join}}</template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{row}">{{row.status | toConverter('NOTICE_STATUS')}}</template>
      </el-table-column>
      <el-table-column label="最后编辑" align="center">
        <template slot-scope="{row}">{{row.lastOperator}}</template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300px">
        <template slot-scope="{row}">
          <el-button
            v-if="roleCheck('edit')"
            type="text"
            @click="openDialog({dialogName: 'notice-edit',
                     props: row
                     })"
          >编辑</el-button>
          <el-button v-if="roleCheck('del')" type="text" @click="handleDelete(row)">删除</el-button>
          <el-button
            type="text"
            @click="toggleStatus(row)"
            v-if="row.status !== 2 && roleCheck('switch')"
          >收回</el-button>
          <el-button type="text" @click="toggleStatus(row)" v-else-if="roleCheck('switch')">恢复</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        background
        @size-change="gridSizeChange"
        @current-change="gridCurrentChange"
        :current-page="filters.page"
        :page-sizes="gridPageSize"
        :page-size="filters.size"
        :layout="gridLayout"
        :total="tableData.total"
      ></el-pagination>
    </div>

    <el-dialog :visible.sync="dialogVisible" :before-close="() => {dialogVisible = false}">
      <notice-edit
        style="max-height:60vh; overflow: auto"
        :id="dialogProps.id"
        :row-data="dialogProps"
        @on-success="dialogVisible = false;
                   doGet({action: 'getGrid'})"
        v-if="dialogName === 'notice-edit'"
      ></notice-edit>
    </el-dialog>
  </div>
</template>

<script>
import { form, grid, dialog } from '@/build';

import {
  noticeOperatorApi,
  noticeAnnouncementListApi,
  noticeAnnouncementDeleteApi,
  noticeAnnouncementToggleStatus,
} from '@/services/api/notice';

import NoticeEdit from './noticeEdit';

export default {
  name: 'announcement-list',

  mixins: [form, grid, dialog],

  components: {
    NoticeEdit,
  },

  props: {
    departmentId: Number,
    workId: Number,
  },

  data() {
    return {
      operatorList: [],
      tableData: {
        list: [],
        total: 0,
      },
      // form: {
      //   operator: undefined,
      //   date: undefined,
      //   type: undefined,
      //   theme: undefined,
      //   name: undefined,
      //   showClient: [],
      //   beginTime: undefined,
      //   endTime: undefined,
      //   time: [
      //     moment().format('YYYY-MM-DD 00:00:00'),
      //     moment().format('YYYY-MM-DD 23:59:59'),
      //   ],
      //   status: undefined,
      // },
      filters: {
        operator: undefined,
        date: undefined,
        type: undefined,
        // theme: undefined,
        name: undefined,
        userType: undefined,
        // beginTime: undefined,
        showClient: [],
        // endTime: undefined,
        status: undefined,
        time: [
          moment().format('YYYY-MM-DD 00:00:00'),
          moment().format('YYYY-MM-DD 23:59:59'),
        ],
        page: 1,
        size: 20,
      },
      filterDateType: false,
    };
  },

  methods: {
    handleDelete({ id }) {
      this.$confirm('确定要删除此公告吗？', '删除公告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          noticeAnnouncementDeleteApi({
            id,
          }).then(([result, data]) => {
            if (result) {
              this.doGet({ action: 'getGrid' });
              this.$message({
                type: 'success',
                message: '删除成功!',
              });
            } else {
              this.$message({
                type: 'error',
                message: `删除失败!${data.message}`,
              });
            }
          });
        })
        .catch(() => {});
    },
    // submitFilterForm() {
    //   let { time, showClient } = this.form;
    //   let beginTime = undefined,
    //     endTime = undefined;
    //   if (!_.isUndefined(time) && _.isArray(time)) {
    //     beginTime = time[0];
    //     endTime = time[1];
    //   }
    //   let newShowClient = undefined;
    //   if (showClient.length) {
    //      newShowClient = showClient.join(",");
    //   }
    //   this.filters = { ...this.form, beginTime, endTime,showClient:newShowClient};
    //   this.gridSearch();
    // },
    selfResetForm(formName) {
      this.resetForm(formName);
      this.gridSearch();
    },

    toggleStatus({ id, status }) {
      const action = status != 2 ? '收回' : '恢复';
      this.$confirm(`确定要${action}此公告吗？`, `${action}公告`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          noticeAnnouncementToggleStatus({
            id,
            status: status != 2 ? 1 : 0,
          }).then(([result, data]) => {
            if (result) {
              this.doGet({ action: 'getGrid' });
              this.$message({
                type: 'success',
                message: `${action}成功!`,
              });
            } else {
              this.$message({
                type: 'error',
                message: `${action}失败!${data.message}`,
              });
            }
          });
        })
        .catch(() => {});
    },
  },

  mounted() {
    this.bindGet(noticeOperatorApi, 'operatorList', {});

    this.bindGet(noticeAnnouncementListApi, 'tableData', {
      action: 'getGrid',
      sendingData: 'filters',
      beforeSend: (data) => {
        const { time, showClient } = data;
        let beginTime;
        let endTime;
        if (time && _.isArray(time)) {
          beginTime = time[0];
          endTime = time[1];
        }
        let newShowClient;
        if (showClient && showClient.length) {
          newShowClient = showClient.join(',');
        }
        return {
          ...data, beginTime, endTime, showClient: newShowClient,
        };
      },
      // afterSuccess: ([result, data]) => {},
    });
    this.getAll();
  },
};
</script>
